$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sjdriverapply/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true ,hidden:true},
			{ label: '司机姓名', name: 'name', index: 'name', width: 50 },
            { label: '手机号', name: 'mobile', index: 'mobile', width: 80 },
            { label: '分公司', name: 'branchCompany', index: 'branch_company', width: 150 },
            { label: '网点', name: 'netPoint', index: 'net_point', width: 120 },
            { label: '性别', name: 'sex', index: 'sex', width: 50,
                formatter:function(v){
                    if(v==0){
                        return "女";
                    }else if(v==1){
                        return "男";
                    }else{
                        return v;
                    }
                }
            },
			{ label: '身份证号', name: 'idCard', index: 'id_card', width: 110 },
			{ label: '年龄', name: 'age', index: 'age', width: 50 },
			{ label: '银行卡号', name: 'bankCardNo', index: 'bank_card_no', width: 80, hidden:true},
			{ label: '身份证照片', name: 'idCardImg', index: 'id_card_img', width: 80, hidden:true},
			{ label: '手持身份证照片', name: 'handCardImg', index: 'hand_card_img', width: 80, hidden:true},
			{ label: '驾驶证照片', name: 'driverLicenseImg', index: 'driver_license_img', width: 80, hidden:true},
			{ label: '行驶证照片', name: 'drivingLicenseImg', index: 'driving_license_img', width: 80, hidden:true },
			{ label: '签约合同照片', name: 'contractImg', index: 'contract_img', width: 80, hidden:true },
			{ label: '加盟金额', name: 'joinMoney', index: 'join_money', width: 60 },
			{ label: '已付金额', name: 'paidMoney', index: 'paid_money', width: 60 },
			{ label: '未付金额', name: 'unpaidMoney', index: 'unpaid_money', width: 60 },
			{ label: '是否审核', name: 'ifExamine', index: 'if_examine', width: 60 ,
                cellattr:function(rowId, val, rawObject, cm, rdata) {
                    if(rawObject.ifExamine==0) {
                        return "style='color:red;font-weight:bold'";
                    }
                },
                formatter:function(v){
                    if(v==0){
                        return "未审核";
                    }else if(v==1){
                        return "已审核";
                    }else{
                        return v;
                    }
                }
            },
			{ label: '审核人', name: 'examinerId', index: 'examiner_id', width: 70 },
			{ label: '审核时间', name: 'examineTime', index: 'examine_time', width: 120 },
			{ label: '备注或审核不通过原因', name: 'remark', index: 'remark', width: 80, hidden:true},
            { label: '审核', width: 60 ,formatter: function(value, options, row){
                return '<input type="button" class="btn btn-primary" onclick="vm.checkAudit('+row.id+','+row.ifExamine+')" value="审核"/>';
            }}
        ],
		viewrecords: true,
        height: 680,
        rowNum: 20,
		rowList : [20,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
    vm.getjqGridBranchCompany();
    // vm.getjqGridNetPoint();
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
        q:{
            branchCompany:null,
            netPoint:null,
            name:null,
            mobile:null
        },
		sjDriverApply: {

        },
        examine:null,
        insuranceExpiry:null,
        imageUrl1: '',
        imageUrl2: '',
        imageUrl3: '',
        imageUrl4: '',
        imageUrl5: '',
        imageUrl6: '',
        imageUrl7: '',
        imageUrl8: '',
        imageUrl9: ''
	},
	methods: {
		query: function () {
			vm.reload();
		},
        empty: function () {
            vm.q.branchCompany = null;
            vm.q.netPoint = null;
            vm.q.name = null;
            vm.q.mobile = null;
            vm.reload();
        },
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.sjDriverApply = {
                branchCompany:null,
                netPoint:null,
                insuranceExpiryDate:null,
                examineTime:null
			};
            $("#check").hide();
            $("#check2").hide();
            $("#noCheck").show();
            $("#noCheck2").show();
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            $("#check").hide();
            $("#check2").hide();
            $("#noCheck").show();
            $("#noCheck2").show();
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
            var status = true;
            $("#name,#idCard,#bankCarNo,#carstyle,#carno").each(function () {
                var str = $(this).val();
                if (str == null || str == "") {
                    status = false;
                    alert("必传字段不能为空！");
                    $(this).css("background-color", "yellow");
                }
            });
            if(status){
                if(vm.sjDriverApply.examineTime != null && vm.sjDriverApply.examineTime != vm.examine) {
                    vm.sjDriverApply.examineTime = dateChange(vm.sjDriverApply.examineTime);
                }
                if(vm.sjDriverApply.insuranceExpiryDate != null && vm.sjDriverApply.insuranceExpiryDate != vm.insuranceExpiry){
                    vm.sjDriverApply.insuranceExpiryDate = dateChange(vm.sjDriverApply.insuranceExpiryDate);
                }
                var url = vm.sjDriverApply.id == null ? "sjdriverapply/save" : "sjdriverapply/update";
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.sjDriverApply),
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(index){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            }
        },
        sjCheck: function (event){
            if(vm.sjDriverApply.examineTime != null && vm.sjDriverApply.examineTime != vm.examine) {
                vm.sjDriverApply.examineTime = dateChange(vm.sjDriverApply.examineTime);
            }
            if(vm.sjDriverApply.insuranceExpiryDate != null && vm.sjDriverApply.insuranceExpiryDate != vm.insuranceExpiry){
                vm.sjDriverApply.insuranceExpiryDate = dateChange(vm.sjDriverApply.insuranceExpiryDate);
            }
            $.ajax({
                type: "POST",
                url: baseURL + "sjdriverapply/check",
                contentType: "application/json",
                data: JSON.stringify(vm.sjDriverApply),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });

        },
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sjdriverapply/delete",
				    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "sjdriverapply/info/"+id, function(r){
                vm.sjDriverApply = r.sjDriverApply;
                vm.examine = vm.sjDriverApply.examineTime;
                vm.insuranceExpiry = vm.sjDriverApply.insuranceExpiryDate;
                var frontUrl = '/qwj_shop/fileDirect/backManageDriver/';
				vm.imageUrl1 = frontUrl + vm.sjDriverApply.idCardImg;
				vm.imageUrl2 = frontUrl + vm.sjDriverApply.handCardImg;
				vm.imageUrl3 = frontUrl + vm.sjDriverApply.driverLicenseImg;
				vm.imageUrl4 = frontUrl + vm.sjDriverApply.drivingLicenseImg;
				vm.imageUrl5 = frontUrl + vm.sjDriverApply.contractImg;
				vm.imageUrl6 = frontUrl + vm.sjDriverApply.contractImg2;
				vm.imageUrl7 = frontUrl + vm.sjDriverApply.contractImg3;
				vm.imageUrl8 = frontUrl + vm.sjDriverApply.contractImg4;
				vm.imageUrl9 = frontUrl + vm.sjDriverApply.carInsuranceImg;
                // var prevDiv = document.getElementById('preview');
                // prevDiv.innerHTML = '<img src="'+'/qwj_shop/fileDirect/backManageDriver/'+vm.sjDriverApply.idCardImg + '" style="width: 178px;height: 178px;"/>';
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{'branchCompany': vm.q.branchCompany,'netPoint':vm.q.netPoint,
                    'name':vm.q.name, 'mobile':vm.q.mobile},
                page:page
            }).trigger("reloadGrid");
		},
        checkAudit:function(id,ifExamine){
            if(ifExamine == 1){
                alert("此司机信息已通过审核！");
            }else{
                vm.showList = false;
                vm.title = "司机信息审核";
                $("#check").show();
                $("#check2").show();
                $("#noCheck").hide();
                $("#noCheck2").hide();
                vm.getInfo(id);
            }
        },
		uploadImg1: function() {

		},
        handleAvatarSuccess: function(res, file) {
			vm.sjDriverApply.idCardImg = res.url;
            // vm.empBaseinfo.idCardPath = res.url;//URL.createObjectURL(file.raw);
			this.imageUrl1 = URL.createObjectURL(file.raw);
        },
        handleAvatarSuccess2: function(res, file) {
            vm.sjDriverApply.handCardImg = res.url;
            this.imageUrl2 = URL.createObjectURL(file.raw);
        },
        handleAvatarSuccess3: function(res, file) {
            vm.sjDriverApply.driverLicenseImg = res.url;
            this.imageUrl3 = URL.createObjectURL(file.raw);
        },
        handleAvatarSuccess4: function(res, file) {
            vm.sjDriverApply.drivingLicenseImg = res.url;
            this.imageUrl4 = URL.createObjectURL(file.raw);
        },
        handleAvatarSuccess5: function(res, file) {
            vm.sjDriverApply.contractImg = res.url;
            this.imageUrl5 = URL.createObjectURL(file.raw);
        },
        handleAvatarSuccess6: function(res, file) {
            vm.sjDriverApply.contractImg2 = res.url;
            this.imageUrl6 = URL.createObjectURL(file.raw);
        },
        handleAvatarSuccess7: function(res, file) {
            vm.sjDriverApply.contractImg3 = res.url;
            this.imageUrl7 = URL.createObjectURL(file.raw);
        },
        handleAvatarSuccess8: function(res, file) {
            vm.sjDriverApply.contractImg4 = res.url;
            this.imageUrl8 = URL.createObjectURL(file.raw);
        },
        handleAvatarSuccess9: function(res, file) {
            vm.sjDriverApply.carInsuranceImg = res.url;
            this.imageUrl9 = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload: function(file) {

            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                alert('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                alert('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        popBranchCompanySelect:function(){
            utils.openDialogView('分公司列表',$("#windowBranchCompany"),'900px','500px',1);
        },
        getjqGridBranchCompany: function(){
            $("#jqGridBranchCompany").jqGrid({
                url: baseURL + 'psbranchcompany/list',
                datatype: "json",
                colModel: [
                    { label: 'id', name: 'id', index: 'id', width: 50, key: true},
                    { label: '分公司名称', name: 'companyName', index: 'company_name', width: 100 },
                    { label: '分公司营业执照', name: 'companyLicenceImg', index: 'company_licence_img', width: 80 },
                    { label: '分公司地址', name: 'address', index: 'address', width: 150 },
                    { label: '联系电话', name: 'contactNumber', index: 'contact_number', width: 80 },
                    { label: '联系人', name: 'contactPeople', index: 'contact_people', width: 80 }
                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList : [10,30,50],
                rownumbers: true,
                // rownumWidth: 85,
                autowidth:false,
                multiselect: false,
                pager: "#jqGridPagerBranchCompany",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    // $("#jqGridBranchCompany").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });
		},
        popNetPointSelect:function(){
        	if( vm.sjDriverApply.branchCompanyId == null ) {
                alert("请先选择一个分公司!");
                return ;
			}
            utils.openDialogView('网点列表',$("#windowNetPoint"),'900px','500px',1);
        },
        getjqGridNetPoint: function(branchCompanyId){
            $("#jqGridNetPoint").jqGrid({
                url: baseURL + 'psnetpoint/list',
                datatype: "json",
                postData:{'branchCompanyId': branchCompanyId},
                colModel: [
                    { label: 'id', name: 'id', index: 'id', width: 50, key: true},
                    { label: '网点名称', name: 'pointName', index: 'point_name', width: 120 },
                    { label: '所属分公司id', name: 'branchCompanyId', index: 'branch_company_id', width: 80 ,hidden:true},
                    { label: '所属分公司名称', name: 'branchCompany', index: 'branch_company', width: 130 },
                    { label: '网点地址', name: 'address', index: 'address', width: 300 },
                    { label: '营业时间', name: 'shopHours', index: 'shop_hours', width: 80 },
                    { label: '收件时间', name: 'receivingTime', index: 'receiving_time', width: 80 },
                    { label: '电话', name: 'telphone', index: 'telphone', width: 80 },
                    { label: '经度', name: 'longitude', index: 'longitude', width: 80 ,hidden:true},
                    { label: '纬度', name: 'latitude', index: 'latitude', width: 80 ,hidden:true},
                    { label: '省', name: 'province', index: 'province', width: 80,hidden:true },
                    { label: '市', name: 'city', index: 'city', width: 80 ,hidden:true},
                    { label: '区', name: 'country', index: 'country', width: 80 ,hidden:true},
                    { label: '高德云图id(高德检索用)', name: 'gaoId', index: 'gao_id', width: 80 ,hidden:true}
                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList : [10,30,50],
                rownumbers: true,
                // rownumWidth: 25,
                autowidth:false,
                multiselect: false,
                pager: "#jqGridPagerNetPoint",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    // $("#jqGridNetPoint").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });
		}

	}
});

function dateChange(dateTime){
    if(dateTime != null) {
        var seperator1 = "-";
        var year = dateTime.getFullYear();
        var month = dateTime.getMonth() + 1;
        var strDate = dateTime.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }else{
        return null;
    }
};

// 判断手机号码
$("#mobile").blur(function () {
    var str = $(this).val();
    var re = /^1([3578]\d|4[57])\d{8}$/;
    if (str != null && str != "") {
        if(!re.test(str)) {
            alert("手机号格式不正确！");
            $(this).css("background-color","yellow");
        }
    } else {
        alert("请填写手机号！");
        $(this).css("background-color","yellow");
    }
});

//不为空验证
$("#name,#idCard,#bankCarNo,#carstyle,#carno").blur(function() {
        var str = $(this).val();
        if (str == null || str == "") {
            alert("必传字段不能为空！");
            $(this).css("background-color","yellow");
        }
});


$("input[ type='text' ] ").focus(function(){
    $(this).css("background-color","white");
});

/** 分公司弹窗确定和关闭按钮处理 **/
$("#addBranchCompany").click(function(){
    //判断是否选中了数据
    var id=$("#jqGridBranchCompany").jqGrid('getGridParam','selrow');
    if(id==null){
        alert("请选择一条记录!");
        return ;
    }
    var rowData = $("#jqGridBranchCompany").jqGrid('getRowData',id);
    vm.sjDriverApply.branchCompany = rowData.companyName;
    vm.sjDriverApply.branchCompanyId = rowData.id;
    utils.closeCurrentPage();
    vm.getjqGridNetPoint(vm.sjDriverApply.branchCompanyId);
});

$("#closeBranchCompany").click(function(){
    utils.closeCurrentPage();
});

/** 网点弹窗口确定和关闭按钮处理 **/
$("#addNetPoint").click(function(){
    //判断是否选中了数据
    var id=$("#jqGridNetPoint").jqGrid('getGridParam','selrow');
    if(id==null){
        alert("请选择一条记录!");
        return ;
    }
    var rowData = $("#jqGridNetPoint").jqGrid('getRowData',id);
    alert("所选网点名为:"+rowData.pointName);
    vm.sjDriverApply.netPointId = rowData.id;
    vm.sjDriverApply.netPoint = rowData.pointName;
    utils.closeCurrentPage();
});

$("#closeNetPoint").click(function(){
    utils.closeCurrentPage();
});


